package com.hotelsystem.reservations.helpers;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;

public class FileUtility {
	/**
	 * Copies the file pointed by source into the file pointed by destination.if
	 * the file pointed by destination already exists noting happens.
	 * @author Asen Asenov
	 * @param source
	 * @param destination
	 * @throws IOException
	 */
	static void copy(String source, String destination) throws IOException {
		File src = new File(source);
		File dst = new File(destination);
		if(dst.exists())return;
		Files.copy(src.toPath(), dst.toPath(), StandardCopyOption.COPY_ATTRIBUTES);
	}
	
	/**
	 * Moves the file pointed by source into the file pointed by destination.if
	 * the file pointed by destination already exists noting happens.
	 * @author Asen Asenov
	 * @param source
	 * @param destination
	 * @throws IOException
	 */
	static void move(String source, String destination) throws IOException {
		File src = new File(source);
		File dst = new File(destination);
		if(dst.exists())return;
		Files.move(src.toPath(), dst.toPath(), StandardCopyOption.ATOMIC_MOVE);
	}
	
	/**
	 * 
	 * @author Viktor Mitev
	 *
	 */
	public static abstract class FileActionExecuter {
		
		/**
		 * Applies action on file in given directory
		 * @param file - applies action on this file
		 */
		public abstract void applyAction(File file);
		
	}
	
	/**
	 * Loops over files in given directory and executes action for every file
	 * @param path - the source directory
	 * @param executer - instance of the static abstract class FileActionExecuter
	 */
	public void loopOverFiles(String path, FileActionExecuter executer) {
		
		ArrayList<File> files = getFilesFromDirectory(path);
		for(File file : files) {
			executer.applyAction(file);
		}
	
	}
	
	/**
	 * Lists all files from given directory
	 * @param sourcePath - the source directory
	 * @return - ArrayList with all the files in the directory
	 */
	private ArrayList<File> getFilesFromDirectory(String sourcePath) {
		File sourceDir = new File(sourcePath);
		
		File[] files = sourceDir.listFiles();
		ArrayList<File> filesAsArrayList = new ArrayList<File>(Arrays.asList(files));
		
		return filesAsArrayList;
	}
}
